package com.laikan.reader.core.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import com.laikan.library.components.BasicApplication;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.database.DBBook;
import com.laikan.reader.database.DBHistory;

import java.io.File;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2016/9/26.
 */
public class AccountManager {

    private static AccountManager accountManager = new AccountManager();

    private AccountManager() {}

    public static AccountManager getInstance() {
        return accountManager;
    }

    public void clearAccountData() {
        //删除缓存书架书籍
        DBBook.getInstance().clear();
        //删除缓存阅读历史书籍
        DBHistory.getInstance().clear();
        //清除存储键值对
//        SPUtil.getInstance().clearAllItem();
        clearSharePreference();
        File bookContentPath = PublicUtil.getFile(BookFileUtils.BOOKCONTENTPATH);
        //删除缓存数据
        FileUtil.deleteDir(bookContentPath.getPath());
    }

    public boolean isSwitchAccount(String token) {
        return !TextUtils.isEmpty(token) && !token.equals(SPUtil.getString("token", ""));
    }

    private void clearSharePreference() {
       SharedPreferences sp = BasicApplication.getInstance().getSharedPreferences("laikan_sp", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        Map spMap = sp.getAll();
        Set set = spMap.keySet();
        for (Object aSet : set) {
            String hashKey = (String)aSet;
            if (!TextUtils.isEmpty(hashKey) &&
                (hashKey.contains("chaptep_rec")
                 || hashKey.contains("recCurPage")
                 || hashKey.contains("recCurPage")
                 || hashKey.contains("rewardNumberInt")
                 || hashKey.contains("update_message")
                 || hashKey.contains("_lastChapterId")
                 || hashKey.contains("chap_count_")
                 || hashKey.contains("chap_pos_")
                 || hashKey.contains("chapterCount_pos_")
                 || hashKey.contains("chapid_")
                 || hashKey.contains("isDowning_chapter")
                 || hashKey.contains("isDowning_chapter")
                 || hashKey.contains("buyback"))) {
                editor.remove(hashKey);
            }
        }
        editor.commit();
    }
}
